package com.sdtv.basemodule.config.life;

import android.app.Activity;

import java.util.Stack;

/**
 * @ProjectName: MediunFusion
 * @Package: com.sdtv.basemodule.config.life
 * @ClassName: AppManager
 * @Description: activity栈
 * @Author: 小郭同学
 * @CreateDate: 2019-06-28 10:09
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class AppManager {

    private static Stack<Activity> activityStack;

    private volatile static AppManager instance;

    // 获取appmanager实例
    public static AppManager getInstance() {
        if (null == instance) {
            synchronized (AppManager.class) {
                if (null == instance) {
                    instance = new AppManager();
                }
            }
        }
        return instance;
    }

    /**
     * 添加activity到堆栈
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (null == activityStack) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);

    }

    /**
     * 从堆栈中移除指定的activity
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        if (null == activityStack || null == activity) {
            return;
        }
        activityStack.remove(activity);
    }

    /**
     * 结束指定的activity
     *
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (null == activityStack || null == activity) {
            return;
        }
        activityStack.remove(activity);
        activity.finish();
        activity = null;
    }

    /**
     * 获取第一个的activity -栈顶的activity
     *
     * @return
     */
    public Activity getTopActivity() {
        if (null == activityStack || activityStack.isEmpty()) {
            return null;
        }
        return activityStack.pop();
    }

    /**
     * 关闭当前的activity --栈顶的
     */
    public void finishActivity() {
        if (null == activityStack || activityStack.isEmpty()) {
            return;
        }
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 关闭所有的activity
     */
    public void finishAllActivity() {
        if (null == activityStack || activityStack.isEmpty()) {
            return;
        }
        for (Activity activity : activityStack) {
            finishActivity(activity);
        }
    }

    /**
     * 退出应用程序
     */
    public void exitApp() {
        try {
            //finish所有activity
            finishAllActivity();
            //杀死进程
//            android.os.Process.killProcess(android.os.Process.myPid());
//            System.exit(0);
        } catch (Exception ignored) {

        }
    }
}
